<?php
/**
 * @link https://www.kancloud.cn/cleverstone/ymb2
 * @copyright Copyright (c) 2020 Yii Manager Software LLC
 */

namespace common\models;

use Yii;
use common\helper\Http;

/**
 * 操作日志服务类
 * @author cleverstone
 * @since ym2.0
 */
class TlogService
{
    /**
     * 防止同一路由重复写入操作日志
     * @var array
     */
    private static $_alreadyRoute = [];

    /**
     * 新增操作日志记录
     * @param int $userId 后台用户ID
     * @param string $route 权限路由
     * @param string $category 日志分类
     * @param string $message 日志消息
     * @return void
     * @throws \yii\db\Exception
     */
    public static function write($userId, $route, $category, $message)
    {
        if (in_array($route, self::$_alreadyRoute)) {
            return;
        }

        $userClient = Http::getClientInfo();
        $prefix = '[ '
            . (Yii::$app->request->userIP ?: '-') . ' ]  [ '
            . $userClient->platform() . ' ] [ '
            . $userClient->browser() . " {$userClient->browserVersion()}"
            . ' ]';

        $model = new Tlog();
        $model->setScenario('SCE_Tlog_Create');

        $model->aid = $userId;
        $model->route = $route;
        $model->category = $category;
        $model->prefix = $prefix;
        $model->message = $message;
        $model->save();
        if ($model->hasErrors()) {
            Yii::error($model->error, __METHOD__);
        }

        self::$_alreadyRoute[] = $route;
    }
}